#include "pch.h"
#include "States.h"
#include "ErrorCodes.h"

using namespace Platform;

using namespace DXBase;
using namespace DXBase::D3D;

SamplerState::SamplerState()
	: desc(CD3D11_DEFAULT())
{
	watcher.Target = this;
}
void SamplerState::Reload()
{
	if (!Context)
		throw ExHelper::CreateException(ErrorCodes::ContextNotSet);
	if (!mState.Get())
		HR2Ex(Context->m_d3dDevice->CreateSamplerState(&desc, &mState));
}


RasterizerState::RasterizerState()
	: desc(CD3D11_DEFAULT())
{
	watcher.Target = this;
}
void RasterizerState::Reload()
{
	if (!Context)
		throw ExHelper::CreateException(ErrorCodes::ContextNotSet);
	if (!mState.Get())
		HR2Ex(Context->m_d3dDevice->CreateRasterizerState(&desc, &mState));
}


BlendState::BlendState()
	: desc(CD3D11_DEFAULT())
{
	watcher.Target = this;
	WeakReference wme(this);
	std::function<RENDER_TARGET_BLEND_DESC(UINT)> getvalue = [wme] (UINT i) -> RENDER_TARGET_BLEND_DESC
	{
		RENDER_TARGET_BLEND_DESC res;
		auto me = wme.Resolve<BlendState>();
		if (me)
			InitSrcDst(me->desc.RenderTarget[i], res);
		return res;
	};
	std::function<void(UINT,RENDER_TARGET_BLEND_DESC)> setvalue = [wme] (UINT i, RENDER_TARGET_BLEND_DESC value)
	{
		auto me = wme.Resolve<BlendState>();
		if (me)
		{
			InitSrcDst(value, me->desc.RenderTarget[i]);
			me->Reset();
		}
	};
	pRenderTargets = ref new DataPointerView<RENDER_TARGET_BLEND_DESC>(8, getvalue, setvalue);
}
void BlendState::Reload()
{
	if (!Context)
		throw ExHelper::CreateException(ErrorCodes::ContextNotSet);
	if (!mState.Get())
		HR2Ex(Context->m_d3dDevice->CreateBlendState(&desc, &mState));
}

DepthStencilState::DepthStencilState()
	: desc(CD3D11_DEFAULT())
{
	watcher.Target = this;
}
void DepthStencilState::Reload()
{
	if (!Context)
		throw ExHelper::CreateException(ErrorCodes::ContextNotSet);
	if (!mState.Get())
		HR2Ex(Context->m_d3dDevice->CreateDepthStencilState(&desc, &mState));
}

